var express = require('express');
const { ValidationError } = require('../utils/errors');
var router = express.Router();
const {loginService, updateAdminService} = require("../service/adminService");
const {formatResponse, analysisToken} = require("../utils/tool");

// 登录
router.post('/login', async function(req, res, next) {
  // 首先应该有一个验证码
  if(req.body.captcha.toLowerCase() !== req.session.captcha.toLowerCase()) {
    // 验证码错误
    throw new ValidationError("验证码错误");
  }
  // 验证码通过
  const result = await loginService(req.body);
  if(result.token) {
    res.setHeader("authentication", result.token)
  }
  res.send(formatResponse(0, "", result.data));
});

// 恢复登录状态
router.get("/whoami", async function(req, res, next) {
  // 1. 从客户端的请求拿到 token,解析token，还原成有用的信息
  const token = analysisToken(req.get("Authorization"));
  // 2. 返回给客户端
  res.send(formatResponse(0, "", {
    "loginId": token.loginId,
    "name": token.name,
    "id": token.id
  }))
})

// 修改用户信息
router.put("/", async function (req, res, next) {
  res.send(await updateAdminService(req.body));
})

module.exports = router;